package fr.cephb.operonj.tools.cmdline;

import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;
import fr.cephb.operonj.core.db.database.BuildDB;

public class BuildDrop extends AbstractApplication
	{
	
	BuildDrop()
		{
		super.envCfg.setAllowCreate(false);
		super.envCfg.setReadOnly(false);
		super.envCfg.setTransactional(true);
		}

	
	private int run(String args[]) throws Exception
		{
		int optind= processArgs(args);
		if(optind==args.length)
			{
			System.err.println("build.ids missing");
			return -1;
			}
		Transaction txn=null;
		BuildDB db=null;
		try
			{

			open();
			DatabaseConfig cfgConfig= new DatabaseConfig();
			cfgConfig.setAllowCreate(false);
			cfgConfig.setReadOnly(false);
			cfgConfig.setTransactional(true);
			txn=getEnvironment().beginTransaction(null, null);
			db=new BuildDB(getEnvironment(), txn, null, cfgConfig);
			
			while(optind<args.length)
				{
				
				Integer id=Integer.parseInt(args[optind++]);
				LOG.info("removing build.id:"+id);
				OperationStatus status= db.delete(txn, id);
				if(status!=OperationStatus.SUCCESS)
					{
					LOG.warning("Not found build.id:"+id);
					System.err.println("not found (build.id:"+id+")");
					continue;
					}
				LOG.info("removed build.id:"+id);
				}
			txn.commit();
			}
		catch(Exception err)
			{
			if(txn!=null) txn.abort();
			throw err;
			}
		finally
			{
			if(db!=null) db.close();
			}
		close();
		return 0;
		}
	
	
	public static void main(String[] args)
		{
		try
			{
			BuildDrop app= new BuildDrop();
			app.run(args);
			}
		catch (Exception err)
			{
			err.printStackTrace();
			}
		}
	}
